<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { Plus, Close } from "@element-plus/icons-vue"
import { ref, reactive } from "vue";
import { useRouter } from 'vue-router';
import service from "~/service";

import type { ElForm, ElUpload } from 'element-plus';

type FormInstance = InstanceType<typeof ElForm>
type UploadInstance = InstanceType<typeof ElUpload>
type RegisterInfo = HttpBkhc.RegisterInfo & { confirmPassword?: string }
type PicType = 'idCardPicFront' | 'idCardPicBack' | 'businessLicensePic'
const formData = reactive<RegisterInfo>({
    userType: 1,
    username: '',
    password: '',
    confirmPassword: '',
    phone: '',
    identity: 3,
    idCardNo: '',
    idCardName: '',
    idCardPicFront: '',
    idCardPicBack: '',
    businessLicensePic: '',
})

const validateConfirmPassword = (rule: any, value: any, callback: any) => {
    if (value !== formData.password) {
        callback(new Error("确认密码与设置密码不一致"))
    } else {
        callback()
    }
}

const formRules = {
    username: [{
        required: true, message: '用户名必填', trigger: 'blur'
    },
    {
        min: 6, max: 32, message: '用户名长度必须是6到32个字符之间', trigger: 'blur'
    }],
    password: [{
        required: true, message: '密码必填', trigger: 'blur'
    },
    {
        pattern: /^(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{6,32}$/,
        message: '密码长度必须包含数字、大小写英文字母是6到32个字符之间',
        trigger: 'blur'
    }],
    confirmPassword: [{
        required: true, message: '确认密码必填', trigger: 'blur'
    }, {
        validator: validateConfirmPassword, trigger: 'blur'
    }],
    phone: [{
        required: true, message: '手机号码必填', trigger: 'blur'
    },
    {
        pattern: /^1[0-9]{10}$/, message: '手机号格式不正确', trigger: 'blur'
    }],
    identity: [{
        required: true, trigger: 'change'
    }],
    idCardName: [{
        required: true, message: '姓名必填', trigger: 'blur'
    },
    {
        pattern: /^[\u4e00-\u9fa5]{2,4}$/, message: '姓名输入有误，请输入2到4个中文字符', trigger: 'blur'
    }],
    idCardNo: [{
        required: true, message: '身份证号必填', trigger: 'blur'
    },
    {
        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '身份证号格式不正确', trigger: 'blur'
    }]
}

const router = useRouter()
const formRef = ref<FormInstance>()

const handleConfirm = async (formEl?: FormInstance) => {
    if (!formEl) {
        return
    }
    try {
        let errorMessage = ''
        if (formData.idCardPicFront === '' || formData.idCardPicBack === '') {
            errorMessage = '请上传身份证'
        } else if (formData.identity === 1 && formData.businessLicensePic === '') {
            errorMessage = '请上传营业执照'
        }
        if (errorMessage) {
            ElMessage({
                type: 'error',
                message: errorMessage
            })
            return
        }
        const result = await formEl.validate();
        if (result) {
            const res = await service.syetem.register(formData)
            if (res.code === 200) {
                ElMessage({
                    message: '注册成功，将跳转到登录页面. . .',
                    type: 'success',
                })
                setTimeout(() => {
                    router.push({
                        path: '/login'
                    })
                }, 2000);
            }
            else if (res.code === 202) {
                ElMessage({
                    message: '对不起！用户名已存在',
                    type: 'error',
                })
            } else {
                ElMessage({
                    message: res.msg,
                    type: 'error',
                })
            }
        }
    } catch (error: any) {
        if (error.username || error.password || error.confirmPassword || error.phone) {
            return
        }
        let message = ''
        if (error.idCardName) {
            message = `${formData.identity === 3 ? '真实' : '法人'}${error.idCardName[0].message}`
        }
        else if (error.idCardNo) {
            message = error.idCardNo[0].message
        }
        ElMessage({
            type: 'error',
            message
        })
    }
}

const uploadFileUrl = service.file.getFileUploadUrl()
const fileCardFront = ref()
const fileCardBack = ref()
const businessLicense = ref()
const handleRemoveFile = (type: PicType, UploadEl?: UploadInstance) => {
    formData[type] = '';
    UploadEl?.clearFiles()
}

const handleFileUplaodSuccess = (type: PicType) => {
    return (res: any) => {
        if (res.code === 200 && res.data) {
            formData[type] = res.data.fileId;
        }
    }
}

</script>

<template>
    <div class="full-layout partner-register">
        <div class="nav">业务合伙人注册</div>
        <div class="box">
            <el-form
                ref="formRef"
                :rules="formRules"
                :model="formData"
                class="form"
                label-width="125px"
                label-position="left"
            >
                <el-form-item label="用户名：" prop="username">
                    <el-input v-model="formData.username" placeholder="用户名" class="small-width"></el-input>
                </el-form-item>
                <el-form-item label="密码：" prop="password">
                    <el-input
                        v-model="formData.password"
                        placeholder="密码"
                        type="password"
                        class="small-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="确认密码：" prop="confirmPassword">
                    <el-input
                        v-model="formData.confirmPassword"
                        placeholder="确认密码"
                        type="password"
                        class="small-width"
                    ></el-input>
                </el-form-item>
                <el-form-item label="手机号码：" prop="phone">
                    <el-input v-model="formData.phone" placeholder="手机号码" class="small-width"></el-input>
                </el-form-item>
                <el-form-item label="身份选择：" prop="identity">
                    <el-radio-group v-model="formData.identity">
                        <el-radio :label="3">个人</el-radio>
                        <el-radio :label="1">企业</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item prop="idCardName" :show-message="false">
                    <el-input
                        v-model="formData.idCardName"
                        :placeholder="formData.identity === 3 ? '真实姓名(2到4个中文字符)' : '法人姓名(2到4个中文字符)'"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="idCardNo" :show-message="false">
                    <el-input
                        v-model="formData.idCardNo"
                        :placeholder="formData.identity === 3 ? '身份证号' : '法人身份证号'"
                    ></el-input>
                </el-form-item>
                <el-form-item prop="partnerId" class="form-item-upload">
                    <el-upload
                        ref="fileCardFront"
                        :action="uploadFileUrl"
                        list-type="picture-card"
                        :limit="1"
                        :multiple="false"
                        :on-success="handleFileUplaodSuccess('idCardPicFront')"
                        class="upload"
                    >
                        <template #default>
                            <Plus class="icon" />
                            <span>上传身份证正面</span>
                        </template>
                        <template #file="{ file }">
                            <div class="file">
                                <img class="img" :src="file.url" />
                                <div
                                    class="remove"
                                    @click="handleRemoveFile('idCardPicFront', fileCardFront)"
                                >
                                    <Close class="icon" />
                                </div>
                            </div>
                        </template>
                    </el-upload>
                    <el-upload
                        ref="fileCardBack"
                        :action="uploadFileUrl"
                        list-type="picture-card"
                        :limit="1"
                        :multiple="false"
                        :on-success="handleFileUplaodSuccess('idCardPicBack')"
                        class="upload"
                    >
                        <template #default>
                            <Plus class="icon" />
                            <span>上传身份证反面</span>
                        </template>
                        <template #file="{ file }">
                            <div class="file">
                                <img class="img" :src="file.url" />
                                <div
                                    class="remove"
                                    @click="handleRemoveFile('idCardPicBack', fileCardBack)"
                                >
                                    <Close class="icon" />
                                </div>
                            </div>
                        </template>
                    </el-upload>
                    <el-upload
                        v-if="formData.identity === 1"
                        ref="businessLicense"
                        :action="uploadFileUrl"
                        list-type="picture-card"
                        :limit="1"
                        :multiple="false"
                        :on-success="handleFileUplaodSuccess('businessLicensePic')"
                        class="upload top"
                    >
                        <template #default>
                            <Plus class="icon" />
                            <span>上传营业执照</span>
                        </template>
                        <template #file="{ file }">
                            <div class="file">
                                <img class="img" :src="file.url" />
                                <div
                                    class="remove"
                                    @click="handleRemoveFile('businessLicensePic', businessLicense)"
                                >
                                    <Close class="icon" />
                                </div>
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" class="button" @click="handleConfirm(formRef)">提 交</el-button>
                    <el-button class="button">保 存</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.partner-register {
    .box {
        max-width: 1200px;
        margin: 24px auto 0px;
        display: flex;
        justify-content: center;
        .form {
            width: 625px;
            margin-left: 80px;
            --el-text-color-regular: rgba(0, 0, 0, 0.85);
            .button {
                border-radius: 2px;
            }
            .small-width {
                width: 295px;
            }
            .form-item-upload {
                .upload {
                    height: 148px;
                    width: 49%;
                    overflow: hidden;
                    .icon {
                        width: 16px;
                        height: 16px;
                    }
                    .file {
                        position: relative;
                        color: #fff;
                        height: 100%;
                        .img {
                            height: 100%;
                            width: 100%;
                        }
                        .remove {
                            position: absolute;
                            top: 0px;
                            right: 0px;
                            width: 28px;
                            height: 28px;
                            background: #ff4d4f;
                            border-radius: 0px 0px 0px 14px;
                            display: flex;
                            justify-content: center;
                            align-items: center;
                            cursor: pointer;
                        }
                    }
                    :deep(.el-upload--picture-card) {
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        width: 100%;
                    }
                    :deep(.el-upload-list .el-upload-list__item) {
                        margin: 0px;
                        height: 100%;
                        width: 100%;
                    }
                }
                .top {
                    margin-top: 12px;
                }
                :deep(.el-form-item__content) {
                    justify-content: space-between;
                }
            }
            :deep(.el-input__inner) {
                height: 34px;
                line-height: 34px;
            }
            :deep(.el-form-item__error) {
                top: -2px;
                left: 295px;
                line-height: 34px;
                width: 34px;
                white-space: nowrap;
                padding-left: 8px;
            }
        }
    }
}
</style>
